package com.ms.p2p.controller.wap;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.CommonUtil;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.SpringContextHolder;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.loan.Loan;
import com.ms.p2p.entity.loan.LoanCategory;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import com.ms.p2p.service.RSAService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chensk on 2017/11/28.
 */
@Controller
@RequestMapping({ "/wap/bid" })
public class WapLoanController extends  WapBaseController{
    @Reference
    private LoanProvider loanProvider;
    @Reference
    private MemberAccountProvider memberAccountProvider;
   private static int i=0;
    @Reference
    EvcProvider evcProvider;
    @Reference
    private LoanStayProvider loanStayProvider;

    @Reference
    private MemberProvider memberProvider;
    @Reference
    private LoanTenderRecordProvider loanTenderRecordProvider;
    @Reference
    private CertiFiCationProvider certificationProvider;

    @Reference
    private PasswordProvider passwordProvider;
    @Reference
    private LoanCategoryProvider loanCategoryProvider;
    @Reference
    private RedPacketProvider redPacketProvider ;
    @RequestMapping("/loanlist")
    public String loan(HttpServletRequest request, HttpSession session,  @RequestParam(value = "loanCategory", required = false) Integer loanCategory) {
        request.setAttribute("loanCategory",loanCategory);
        return "wap/loan/loan";

    }
    @RequestMapping({"/loanAjax"})
    @ResponseBody
    public String loanAjax(
            @RequestParam(value = "currentPage", required = false) Integer currentPage,
            @RequestParam(value = "borrowStatus", required = false) Integer borrowStatus,
            @RequestParam(value = "pay_style", required = false) Integer pay_style,
            @RequestParam(value = "timeLimitBegin", required = false) Integer timeLimitBegin,
            @RequestParam(value = "timeLimitEnd", required = false) Integer timeLimitEnd,
            @RequestParam(value = "rateBegin", required = false) Integer rateBegin,
            @RequestParam(value = "rateEnd", required = false) Integer rateEnd,
            @RequestParam(value = "time_limit", required = false) Integer time_limit,
            @RequestParam(value = "rate", required = false) String rate,
            @RequestParam(value = "lowestAccount", required = false) Integer lowestAccount,
            @RequestParam(value = "lowestAccountBegin", required = false) Integer lowestAccountBegin,
            @RequestParam(value = "lowestAccountEnd", required = false) Integer lowestAccountEnd,
            @RequestParam(value = "loanCategory", required = false) Integer loanCategory

    ){
        List<LoanCategory> types = loanCategoryProvider
                .findAll();
        PageBean borrowPage = new PageBean();
        if (currentPage != null) {
            borrowPage.setCurrentPage(currentPage);
        }
        List<Map<String, Object>> borrows = null;
        borrows = loanProvider.findPager(null, null, null, loanCategory, borrowStatus, timeLimitBegin, timeLimitEnd, rateBegin, rateEnd, lowestAccountBegin, lowestAccountEnd, pay_style, null, null, borrowPage);
        borrowPage.setTotalCount(loanProvider.findCount(null, null, null, loanCategory, borrowStatus, timeLimitBegin, timeLimitEnd, rateBegin, rateEnd, lowestAccountBegin, lowestAccountEnd, pay_style, null, null));
        FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
        String templatePath = Constants.TEMPLATE_WAP_LOAN_ITEM;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = null;
        StringBuilder content = new StringBuilder();
        try {

            template = configuration.getTemplate(templatePath, "utf-8");
            HashMap loan = new HashMap();
            loan.put("loans",borrows);
            content.append(FreeMarkerTemplateUtils.processTemplateIntoString(template, loan));
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (TemplateException e) {
            e.printStackTrace();
        }

        return  content.toString();


    }
    /**
     * 我要投资
     */
    @RequestMapping({"/detail/{borrowId}"})
    public String toLoanDetail(@PathVariable String borrowId, Model model) {
        Member member = getCurrentUser();
        Account account = new Account();
        Loan loan = loanProvider.findById(borrowId);
        if (member != null) {
            account = memberAccountProvider.findByUserId(member.getId());
            if(loan.getRed_packet_status()==1){
                PageBean page = new PageBean();
                page.setPageSize(0);
                //0表示未过期
                List redpackets =redPacketProvider.findPager(page,"0", member.getId(), loan.getTime_limit());
                model.addAttribute("redpackets", redpackets);
            }

        }
        model.addAttribute("loan", loan);
        model.addAttribute("account", account);
        if(loan.getStatus()==2){
            model.addAttribute("last_time",Long.parseLong(loan.getNd_verify_time())*1000-System.currentTimeMillis());
        }
        //token
        String token = CommonUtil.getUUID();
        model.addAttribute("token", token);
        AppContext.setSessionAttr("TENDER_TOKEN", token);
        return "wap/loan/detail";
    }

}
